package handler

import (
	"gift/api/request"
	"gift/internal/dao"
	"gift/internal/model"
	"gift/internal/utills"
	jwt "gift/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Register(c *gin.Context) {
	var req request.Register
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	user := model.Users{
		Phone:    req.Phone,
		Password: utills.Md5Pwd(req.Password),
	}
	if !dao.Create(&user) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": user,
	})
	return
}

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	user := dao.FindPhone(req.Phone)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	if user.Password != utills.Md5Pwd(req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误",
			"data": nil,
		})
		return
	}
	token, _ := jwt.NewJWT("2210a").CreateToken(jwt.CustomClaims{
		ID: uint(user.Id),
	})
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": token,
	})
	return
}
